ExportStartEnd.php

<?php

namespace Tlf\Scrawl\FileExt;

/**
 * Export code between `// @export_start(key)` and `// @export_end(key)`
 * @featured
 */
class ExportStartEnd {


    public function __construct(){}


    /**
     * Parse a string containing blocks marked by @export_start(key) and @export_end(key). Extract every line in between those two lines. return an array containing key=>value pairs for these exported sections.
     */
    public function get_exports(string $str): array {
        $start = '@export_start(';
        $start_len = strlen($start);

        $exports = [];

        $seek_offset = 0;
        while (($start_pos = strpos($str, $start, $seek_offset)) !== false){
            $substr = substr($str,$start_pos);
            //var_dump($substr);
            //exit;
            $line_end = strpos($substr,"\n");
            if ($line_end === false)continue;
            $start_line = substr($substr,0,$line_end);
            $paren_end = strpos($start_line, ")");
            if ($paren_end === false)continue;
            $key = substr($start_line, $start_len, $paren_end - $start_len);
            if (trim($key)=='' || trim($key) != $key)continue;
            
            $end = '@export_end('.$key.')';

            $end_pos = strpos($substr, $end);

            $start_line_len = strlen($start_line);
            if ($end_pos === false){
                $seek_offset = $start_pos + $start_line_len;
            }

            $section_dirty = substr($substr, $start_line_len+1, $end_pos - $start_line_len);
            $section_last_line_start_pos = strrpos($section_dirty, "\n");
            $section = substr($section_dirty, 0, $section_last_line_start_pos);

            //var_dump($key);
            //echo "\n\n$section\n\n";

            $exports[$key] = \Tlf\Scrawl\Utility\Main::trimTextBlock($section);

            $seek_offset = $start_pos + $start_line_len + strlen($section_dirty) + strlen($end);

        }

        return $exports;

    }

}